<template>
  <div class="canvas-container">
    <!-- 画布 -->
    <div>
      <div class="canvas-wrapper">
        <canvas ref="canvas"></canvas>
      </div>
    </div>

    <!-- 控件按钮 -->
    <div class="controls">
      <input type="file" multiple @change="uploadImage" accept="image/*" />
      <el-button type="primary" @click="addText">添加文字</el-button>
      <el-button type="primary" @click="addArrow">添加箭头</el-button>
      <!-- <el-button  type="primary" @click="saveCanvas">保存数据</el-button>
      <el-button  type="primary" @click="loadCanvas">加载数据</el-button> -->

      <el-button slot="reference" type="danger" @click="clearCanvas">清空画布</el-button>

      <!-- 新增删除选中元素按钮 -->
      <el-button type="warning" @click="deleteSelectedElement">删除选中元素</el-button>
      <!-- <el-button  type="primary" @click="saveAsImage">保存为图片</el-button> -->
    </div>
    <!-- 加载提示 -->
    <div v-if="isLoading" class="loading">加载中...</div>
    <!-- 显示保存的图片 -->
    <!-- <div v-if="savedImageUrl" class="saved-image">
      <img :src="savedImageUrl" alt="Saved Canvas Image" />
    </div> -->
  </div>
</template>

<script>
import { fabric } from "fabric";

export default {
  props: {
    // 弹框的表单信息
    form: {
      type: Object,
      default: () => {}
    },
  },
  data() {
    return {
      canvas: null, // 画布实例
      savedData: null, // 存储的画布数据
      isLoading: false, // 加载状态
      savedImageUrl: null, // 图片路径
    };
  },
  mounted() {
    // 初始化 Fabric 画布
    this.canvas = new fabric.Canvas(this.$refs.canvas, {
      width: 900,
      height: 700,
      backgroundColor: "#f8f8f8",
    });
    // 调用方法加载画布数据
    this.loadCanvas(this.form.leader);
  },
  methods: {
    /** 上传图片到画布 */
    uploadImage(event) {
      if (!event || !event.target || !event.target.files) {
        console.error("文件上传错误，event 未定义");
        this.$message.error("文件上传错误，event 未定义");
        return;
      }
      const files = event.target.files;
      for (let file of files) {
        if (!this.isValidImageFile(file)) {
          console.error(`不支持的文件类型: ${file.name}`);
          this.$message.error(`不支持的文件类型: ${file.name}`);
          continue;
        }
        const reader = new FileReader();
        reader.onload = (e) => {
          if (fabric && fabric.Image) {
            fabric.Image.fromURL(e.target.result, (img) => {
              img.set({
                left: 100,
                top: 100,
                scaleX: 0.5,
                scaleY: 0.5,
                selectable: true,
              });
              this.canvas.add(img);
            });
          } else {
            console.error("fabric.Image 未正确加载");
            this.$message.error("fabric.Image 未正确加载");
          }
        };
        reader.readAsDataURL(file);
      }
    },
    /** 检查文件是否为有效的图片类型 */
    isValidImageFile(file) {
      const validTypes = ["image/jpeg", "image/png", "image/gif"];
      return validTypes.includes(file.type);
    },
    /** 添加文字 */
    addText() {
      const text = new fabric.IText("输入文字", {
        left: 150,
        top: 150,
        fontSize: 20,
        fill: "black",
        selectable: true,
      });
      this.canvas.add(text);

      this.$message.success("添加文字成功");
    },
    /** 添加箭头 */
    addArrow() {
      const line = new fabric.Line([50, 100, 200, 100], {
        stroke: "red",
        strokeWidth: 5,
        selectable: true,
      });
      const triangle = new fabric.Triangle({
        left: 205,
        top: 92,
        width: 20,
        height: 25,
        fill: "red",
        angle: 90,
      });
      // 组合箭头
      const arrow = new fabric.Group([line, triangle], {
        left: 100,
        top: 100,
        selectable: true,
      });
      this.canvas.add(arrow);
      this.$message.warning("添加箭头成功");
    },
    /** 保存画布数据 */
    saveCanvas() {
      try {
        this.savedData = JSON.stringify(this.canvas.toJSON());
        //localStorage.setItem("fabricCanvas", this.savedData);
        this.$notify({
          title: '成功',
          message: '画布已保存！',
          type: 'success'
        });
        return this.savedData;
      } catch (error) {
        console.error("保存画布数据时出错:", error);
        this.$notify.error({
          title: '错误',
          message: '保存画布数据时出错，请稍后重试！',
        })
        return null;
      }
    },
    /** 加载画布数据 */
    async loadCanvas(imgData) {
      const data = imgData;
      // const data = localStorage.getItem("fabricCanvas");
      if (data) {
        try {
          this.isLoading = true;
          await new Promise((resolve) => {
            this.canvas.loadFromJSON(data, () => {
              this.canvas.renderAll();
              resolve();
            });
          });
          this.$notify({
            title: '成功',
            message: '画布数据加载成功！',
            type: 'success'
          });
        } catch (error) {
          console.error("加载画布数据时出错:", error);
          this.$notify.error({
            title: '错误',
            message: '加载失败，请检查数据是否损坏。',
          })
        } finally {
          this.isLoading = false;
        }
      } else {
        this.$message.warning("没有保存的数据！");
      }
    },
    /** 清空画布 */
    clearCanvas() {
      this.$confirm('确认清空画布？')
        .then(_ => {
          this.canvas.clear();
          this.canvas.setBackgroundColor(
            "#f8f8f8",
            this.canvas.renderAll.bind(this.canvas)
          );
          this.$message.warning("画布已清空！");
        })
        .catch(_ => { });
    },
    /** 删除选中元素 */
    deleteSelectedElement() {
      const activeObject = this.canvas.getActiveObject();
      if (activeObject) {
        this.canvas.remove(activeObject);
        this.canvas.discardActiveObject().renderAll();
        this.$message.error("选中元素已删除！");
      } else {
        this.$message.warning("请先选择要删除的元素。");
      }
    },
    /** 保存画布为图片 */
    saveAsImage() {
      this.savedImageUrl = this.canvas.toDataURL({
        format: "png", // 可以选择 "jpeg" 或 "png"
        quality: 1.0, // 图片质量
      });
      return this.savedImageUrl;

      // // 创建一个临时链接元素进行下载
      // const link = document.createElement("a");
      // link.href = dataURL;
      // link.download = "canvas_image.png"; // 文件名
      // link.click(); // 触发下载
    },
  },

};
</script>

<style scoped>
.canvas-container {
  text-align: center;
  margin-top: 20px;
  position: relative;
}

canvas {
  border: 1px solid #ddd;
}

.controls {
  margin-top: 10px;
  /* width: 135px;
  position: absolute;
  right: 0;
  top: 0; */
}

button {
  margin: 5px;
  /* padding: 8px 12px; */
  cursor: pointer;
}

.loading {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 10px 20px;
  border-radius: 5px;
}

.canvas-wrapper {
  width: 900px;
  margin: 0 auto;
}
</style>